package com.cj.io.bio;

import com.cj.io.Calculator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * ClassName: ServerHandler <br/>
 * Function: 客户端线程 <br/>
 * date: 2018/05/09 11:02 <br/>
 *
 * @author chenj
 * @version 1.0.0
 * @since JDK 1.8
 */
public class ServerHandler implements Runnable {

    private Socket socket;

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
            try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
                String expression;
                String result;
                while (true) {
                    if ((expression = in.readLine()) == null) {
                        break;
                    }
                    System.out.println("服务器收到消息：" + expression);
                    try {
                        result = Calculator.cal(expression).toString();
                    } catch (Exception e) {
                        result = "计算错误：" + e.getMessage();
                    }
                    out.println(result);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }
        }
    }
}
